package com.margo.project.security.token;

import java.util.Date;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtils {
	public static String generateToken(UserToken userToken, int expire) throws Exception {
		String token = Jwts.builder().setSubject(userToken.getUsername())
				.claim(CommonConstants.CONTEXT_USER_ID, userToken.getUserId())
				.claim(CommonConstants.RENEWAL_TIME, new Date(System.currentTimeMillis() + expire / 2))
				.setExpiration(new Date(System.currentTimeMillis() + expire))
				.signWith(SignatureAlgorithm.HS256, CommonConstants.JWT_PRIVATE_KEY).compact();
		return token;
	}

	public static UserToken getInfoFromToken(String token) throws Exception {
		Claims claims = Jwts.parser().setSigningKey(CommonConstants.JWT_PRIVATE_KEY).parseClaimsJws(token).getBody();
		UserToken userToken = new UserToken();
		userToken.setUsername(claims.getSubject());
		userToken.setUserId(claims.get(CommonConstants.CONTEXT_USER_ID).toString());
		return userToken;
	}
	
	public static void main(String[] args) throws Exception {
		UserToken userToken=new UserToken("fxb","1");
		String token=generateToken(userToken,1000000);
		System.out.println(token);
		UserToken infoFromToken=getInfoFromToken(token);
		System.out.println(infoFromToken.getUsername());
		System.out.println(infoFromToken.getUserId());
	}

}
